package com.bml.architect.framework.register;

import com.alibaba.fastjson.JSONObject;
import com.bml.architect.framework.Address;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * zookeeper注册中心
 */
public class ZookeeperRegister {

    private static CuratorFramework client;
    private Map<String, List<Address>> REGISTER = new HashMap<>();


    static {
        client = CuratorFrameworkFactory.newClient("localhost:2181", new RetryNTimes(3, 1000));
        client.start();
    }




    public static void register(String name, Address address) {
        try {
            String result = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
                    .forPath(String.format("/dubbo/service/%s/%s", name, JSONObject.toJSONString(address)), null);
            System.out.println("新注册的ADDRESS=" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<Address> get(String name) {
        List<Address> list = new ArrayList<>();
        try {
            List<String> strings = client.getChildren().forPath(String.format("/dubbo/service/%s", name));
            for (String string : strings) {
                list.add(JSONObject.parseObject(string, Address.class));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;

    }


}


